//
//  YQAddressListVC.m
//  KingRetail
//
//  Created by yuqin on 2019/6/26.
//  Copyright © 2019 yuqin. All rights reserved.
//

#import "YQAddressListVC.h"
#import "YQPayModel.h"
#import "YQAddressDetailCell.h"
#import "YQAddAndEditorVC.h"

@interface YQAddressListVC ()<UITableViewDelegate,UITableViewDataSource,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate>

@property (nonatomic, strong) UITableView *addressTB;
@property (nonatomic, strong) NSMutableArray *addressArr;

@end

@implementation YQAddressListVC

- (NSMutableArray *)addressArr {
    if (!_addressArr) {
        _addressArr = [NSMutableArray array];
    }
    return _addressArr;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.addressTB.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        //数据刷新
        [self loadAddressListData];
    }];
    [self.addressTB.mj_header beginRefreshing];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.btnLeft setTitle:@"收货地址" forState:UIControlStateNormal];
    [self.btnRight setHidden:NO];
    [self.btnRight setTitle:@"添加收货地址" forState:UIControlStateNormal];
    [self loadAddressView];
    
}

//添加收货地址
- (void)pushAction {
    YQ_PUSH([YQAddAndEditorVC new]);
}

- (void)loadAddressView {
    [self.view addSubview:self.addressTB];
    [self.addressTB mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.top.mas_equalTo(NavigationStatusBarHeight);
        make.size.mas_equalTo(CGSizeMake(ScreenWidth, TableView_Height_IPhoneX));
    }];
}

- (void)loadAddressListData {
    [self.addressArr removeAllObjects];
    [SZHTTPSReqManager getRequestWithUrlString:YQ_joiningTogetherUrl(@"address/list") appendParameters:nil successBlock:^(id responseObject) {
        //获取地址
        BaseModel *base = [BaseModel modelWithJson:responseObject];
        if (base.code == 0) {
            //有数据
            for (NSDictionary *dict in responseObject[@"data"]) {
                YQPayModel *model = [YQPayModel mj_objectWithKeyValues:dict];
                [self.addressArr addObject:model];
            }
        }
        
        [self.addressTB.mj_header endRefreshing];
        [self.addressTB reloadData];
    } failureBlock:^(NSError *error) {
        [self.addressTB.mj_header endRefreshing];
    }];
}

- (UITableView *)addressTB {
    
    if (!_addressTB) {
        _addressTB = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _addressTB.delegate = self;
        _addressTB.dataSource = self;
        _addressTB.backgroundColor = MainBackgroundColor;
        YQ_NoDataImg(_addressTB);
        _addressTB.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_addressTB registerNib:[UINib nibWithNibName:YQ_AddressDetailCell bundle:nil] forCellReuseIdentifier:YQ_AddressDetailCell];
    }
    return _addressTB;
}

YQ_ImageForEmptyDataSet(@"暂无数据", NoDataView_Nor);

#pragma mark - 代理
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.addressArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return FIT(120);
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return section == 0?0:FIT(10);
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return nil;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    YQAddressDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:YQ_AddressDetailCell forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    YQPayModel *model = self.addressArr[indexPath.section];
    [cell loadCellDataWithModel:model];
    if ([model.isDefault integerValue] == 1) {
        //默认地址
        cell.defaultBtn.selected = YES;
        [cell.defaultBtn setHidden:NO];
    }else {
        cell.defaultBtn.selected = NO;
        [cell.defaultBtn setHidden:YES];
    }
    cell.EditorAddressBlock = ^{
        YQAddAndEditorVC *editorVC = [[YQAddAndEditorVC alloc] init];
        editorVC.payModel = model;
        YQ_PUSH(editorVC);
    };
//    cell.deleteBtn.tag = indexPath.section+1;
    //删除
    
    cell.DeleteAddressBlock = ^(UITableViewCell * _Nonnull currentCell) {
        //弹框判断是否确认删除
        [JXTAlertView showAlertViewWithTitle:@"温馨提示" message:@"确认删除该地址吗？" cancelButtonTitle:@"取消" otherButtonTitle:@"删除" cancelButtonBlock:^(NSInteger buttonIndex) {
            NSLog(@"cancel");
        } otherButtonBlock:^(NSInteger buttonIndex) {
            //请求数据
            [SZHTTPSReqManager postRequestWithUrlString:YQ_joiningTogetherUrl(@"address/deleteAddr") appendParameters:nil bodyParameters:@{@"id":model.id} successBlock:^(id responseObject) {
                if ([responseObject[@"code"] integerValue] == 0) {
                    //获取点击的是那个cell
//                    DLog(@"cell.deleteBtn.tag = %ld",cell.deleteBtn.tag);
                    //准确获取cell的indexPath
                    NSIndexPath *currentIndexPath = [_addressTB indexPathForCell:currentCell];
                    [self.addressArr removeObjectAtIndex:currentIndexPath.section];
                    [self.addressTB beginUpdates];
                    NSMutableIndexSet *indexSet = [[NSMutableIndexSet alloc] initWithIndex:currentIndexPath.section];
                    [self.addressTB deleteSections:indexSet withRowAnimation:UITableViewRowAnimationFade];
                    [self.addressTB endUpdates];
                    
                }else {
                    [LCProgressHUD showFailure:responseObject[@"msg"]];
                }
            } failureBlock:^(NSError *error) {
                
            }];
        }];
        

    };
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    //点击列表返回上一层 并把值回传
    if ([self.isMeComing integerValue] != 2) {
        YQPayModel *model = self.addressArr[indexPath.section];
        NSDictionary *dict = @{@"name":model.name,
                               @"phone":model.phone,
                               @"addressDetail":model.addressDetail,
                               @"addressId":model.id
                               };
        [[NSNotificationCenter defaultCenter] postNotificationName:@"NSNotficationSendDict" object:nil userInfo:dict];
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}

@end
